package com.platform.common.validator;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.EnumUtil;
import com.platform.common.utils.BeanCopyUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EnumStringValidator implements ConstraintValidator<EnumValid, String> {

    Class<? extends Enum>[] type = null;
    private String enumsKey = null;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        this.type = constraintAnnotation.type();
        this.enumsKey = constraintAnnotation.enumsKey();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //value有值才进行校验
        if (value != null) {
            List<LinkedHashMap> enumMapList = (List<LinkedHashMap>) Stream.of(type).map(EnumUtil::getEnumMap).collect(Collectors.toList());
            if (CollUtil.isEmpty(enumMapList)) {
                return false;
            }
            List<String> values = enumMapList.stream().map(enumMap -> {
                List<Map> list = BeanCopyUtil.deepCopyList(enumMap.values(), MapUtil::newHashMap);
                if (CollUtil.isNotEmpty(list)) {
                    return list.stream().map(obj -> MapUtil.getStr(obj, enumsKey)).collect(Collectors.toList());
                }
                return null;
            }).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList());
            if (CollUtil.isEmpty(values)) {
                return false;
            }
            return values.contains(value);

        } else {
            return true;
        }
    }
}